package org.ttjhome.html.struts.common;

/**
 *
 * EXAMPLE USAGE:
 *  JSPConstants.setConstants( request, AccountBuilderConstants.class, "AccountBuilderConstants" ); 
 *
 * JSP:
 * 	${<key>.CONSTANT_NAME}
 */
import javax.servlet.http.HttpServletRequest;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class JSPConstants
{
	/**
	 * Set the Public static final Constants from a Class into request scope
	 * @param request
	 * @param clazz - the Class object containing the Constants
	 * @param key - the key to put the Constants in scope as
	 */
	public static void setConstants(HttpServletRequest request, Class clazz, String key)
	{
        Field[] allFields = clazz.getDeclaredFields();
        int numFields = allFields.length;
        Map<String,Object> propMap = new HashMap<String, Object>(numFields);
        for (int i = 0; i < numFields; i++)
		{
            Field f = allFields[i];
            int mods = f.getModifiers();
            if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods))
			{
				String name = f.getName();
				try {
					Object value = f.get(null);
					if ( value != null && value instanceof String )
					{
						propMap.put(name, (String)value);
					}
					else if ( value != null )
					{
						propMap.put(name, value.toString() );
					}
				} catch (IllegalAccessException e) {
					// don't add
				}
			}
        }
		request.setAttribute( key, Collections.unmodifiableMap(propMap) );
	}
}

